package com.team06.controller;

import com.team06.pojo.FlightRouteInfo;
import com.team06.pojo.PageResult;
import com.team06.service.FlightSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/flight")
public class FlightSearchController {

    @Autowired
    private FlightSearchService flightService;
    private static final int DEFAULT_PAGE_SIZE = 15;
    private static final int MAX_PAGE_SIZE = 100;
    private static final int MAX_RECORDS = 15000;
    //航班飞机查询
    //全部查询
    @GetMapping("/planes")
    public ResponseEntity<?> getFlightPlanes(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {

        PageResult<Map<String, Object>> result = flightService.getFlightPlanes(page, pageSize);
        return ResponseEntity.ok(Map.of(
                "data", result.getData(),
                "currentPage", result.getCurrentPage(),
                "pageSize", result.getPageSize(),
                "totalRecords", result.getTotalRecords(),
                "totalPages", result.getTotalPages()
        ));
    }
    //通过飞机编号
    @GetMapping("/planes/{cfno}")
    public ResponseEntity<?> getFlightsByAircraftId(
            @PathVariable String cfno,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getFlightsByAircraftId(cfno, page, pageSize));
    }
    //通过飞机机型
    @GetMapping("/planes/cftp")
    public ResponseEntity<?> getFlightsByAircraftType(
            @RequestParam String cftp,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getFlightsByAircraftType(cftp, page, pageSize));
    }

    // 航班时间查询
    @GetMapping("/time")
    public ResponseEntity<?> queryFlightTimeInfo(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.queryFlightTimeInfo(page, pageSize));
    }
    // 通过航班号查询航班时间信息

    @GetMapping("/time/flightNumber")
    public ResponseEntity<?> queryFlightTimeInfoByFlightNumber(
            @RequestParam String flightNumber,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.queryFlightTimeInfoByFlightNumber(flightNumber, page, pageSize));
    }

    // 查询所有机场信息
    // 机场信息查询
    @GetMapping("/airport")
    public ResponseEntity<?> getAllAirports(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getAllAirports(page, pageSize));
    }

    // 通过机场中文名查询机场信息
    @GetMapping("/airport/cnName")
    public ResponseEntity<?> getAirportsByCnName(
            @RequestParam String cnnm,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getAirportsByCnName(cnnm, page, pageSize));
    }

    // 通过机场英文名查询机场信息
    @GetMapping("/airport/enName")
    public ResponseEntity<?> getAirportsByEnName(
            @RequestParam String ennm,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getAirportsByEnName(ennm, page, pageSize));
    }

    //航班航线查询
    @GetMapping("/flight-routes")
    public ResponseEntity<?> getFlightRoutes(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getFlightRoutes(page, pageSize));
    }
    // 通过航班号查询航线信息
    @GetMapping("/flight-routes/{flightNumber}")
    public ResponseEntity<?> getFlightRouteByNumber(@PathVariable String flightNumber) {
        try {
            List<FlightRouteInfo> routes = flightService.getFlightRouteByFlightNumber(flightNumber);
            if (routes.isEmpty()) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(routes);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    //航班航线历史查询
    // 查询所有航线变更历史
    @GetMapping("/route-histories")
    public ResponseEntity<?> getAllRouteHistories(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getAllRouteHistories(page, pageSize));
    }

    // 通过航班号查询航线变更历史
    @GetMapping("/route-histories/flight/{flightNumber}")
    public ResponseEntity<?> getRouteHistoriesByFlightNumber(
            @PathVariable String flightNumber,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getRouteHistoriesByFlightNumber(flightNumber, page, pageSize));
    }

    // 通过变更后始发地查询
    @GetMapping("/route-histories/new-departure/{departure}")
    public ResponseEntity<?> getRouteHistoriesByNewDeparture(
            @PathVariable String departure,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getRouteHistoriesByNewDeparture(departure, page, pageSize));
    }

    // 通过变更后目的地查询
    @GetMapping("/route-histories/new-destination/{destination}")
    public ResponseEntity<?> getRouteHistoriesByNewDestination(
            @PathVariable String destination,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getRouteHistoriesByNewDestination(destination, page, pageSize));
    }

    // 通过变更后经停站查询
    @GetMapping("/route-histories/new-stopover/{stopover}")
    public ResponseEntity<?> getRouteHistoriesByNewStopover(
            @PathVariable String stopover,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getRouteHistoriesByNewStopover(stopover, page, pageSize));
    }
    // 查询所有行李转盘信息
    // 获取所有行李转盘信息
    @GetMapping("/blls-belts")
    public ResponseEntity<?> getAllBllsBelts(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getAllBllsBelts(page, pageSize));
    }

    // 通过航班号查询行李转盘信息
    @GetMapping("/blls-belts/{flid}")
    public ResponseEntity<?> getBllsBeltsByFlightId(
            @PathVariable String flid,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getBllsBeltsByFlightId(flid, page, pageSize));
    }

    // 查询所有登机口信息
    @GetMapping("/boarding-gates")
    public ResponseEntity<?> getAllBoardingGates(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getAllBoardingGates(page, pageSize));
    }

    // 通过航班号查询登机口信息
    @GetMapping("/boarding-gates/flight/{flid}")
    public ResponseEntity<?> getBoardingGatesByFlightId(
            @PathVariable String flid,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getBoardingGatesByFlightId(flid, page, pageSize));
    }

    // 通过登机口编号查询登机口信息
    @GetMapping("/boarding-gates/code/{code}")
    public ResponseEntity<?> getBoardingGatesByCode(
            @PathVariable String code,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int pageSize) {
        if (page < 1 || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
            return ResponseEntity.badRequest().body("参数无效: page必须≥1, pageSize必须1-100");
        }
        return ResponseEntity.ok(flightService.getBoardingGatesByCode(code, page, pageSize));
    }

    // 按日期统计起降架次
    // 获取每日航班起降统计
    @GetMapping("/statistics/daily-flights")
    public ResponseEntity<?> getDailyFlightStatistics(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") String startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") String endDate) {
        try {
            // 验证日期范围
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.parse(endDate);

            if (start.isAfter(end)) {
                return ResponseEntity.badRequest().body("开始日期不能晚于结束日期");
            }

            if (ChronoUnit.DAYS.between(start, end) > 365) {
                return ResponseEntity.badRequest().body("日期范围不能超过1年");
            }

            List<Map<String, Object>> statistics = flightService.getDailyFlightStatistics(startDate, endDate);
            return ResponseEntity.ok(statistics);
        } catch (DateTimeParseException e) {
            return ResponseEntity.badRequest().body("日期格式不正确，请使用yyyy-MM-dd格式");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("查询失败: " + e.getMessage());
        }
    }
}